﻿using Sidvall.Serialization;
using System;
using System.Globalization;
using System.Windows;

namespace Sidvall.UI.Wpf.Converters
{
    public class EnumToVisibilityConverter : ValueToVisibilityConverterBase
    {
        #region Public Members

        #region VisibilityToValue

        protected override object VisibilityToValue(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Visibility))
                return DependencyProperty.UnsetValue;
            switch ((Visibility)value)
            {
                case Visibility.Collapsed:
                case Visibility.Hidden:
                    if (!this.Not)
                        return null;
                    else
                        return GetValue(targetType, parameter);
                default:
                    if (!this.Not)
                        return GetValue(targetType, parameter);
                    else
                        return null;
            }
        }

        #endregion

        #endregion
        #region Private Members

        #region GetValue

        private object GetValue(Type targetType, object parameter)
        {
            if (!Sidvall.SystemContext.Current.CodeManager.IsNullableType(targetType))
            {
                return Enum.Parse(targetType, parameter.ToString(string.Empty));
            }
            else
            {
                var parameterValue = parameter.ToString(string.Empty);
                if (!string.IsNullOrWhiteSpace(parameterValue))
                {
                    targetType = targetType.GenericTypeArguments[0];
                    return Enum.Parse(targetType, parameter.ToString(string.Empty));
                }
                return null;
            }
        }

        #endregion

        #endregion
    }
}
